<template>
	<div class="config-source">
		<div class="config-source_refresh">
			<!-- <div>
        <y-checkbox v-model="value.isRefresh">自动更新请求</y-checkbox>
      </div>
      <div class="config-refresh_interval">
        <y-input
          :height="20"
          v-model="value.refreshInterval"
        ></y-input>
      </div>秒一次 -->
		</div>
		<div class="config-source_data">
			<div class="data-source_title">
				数据源
				<span>{{
					dataSourceType === "数据库"
						? "数据库>" + findDataSourceName(dataSourceListDefault)
						: dataSourceType
				}}</span>
			</div>
			<y-button
				:height="30"
				:hollow="true"
				:showIcon="false"
				:width="100"
				@click="onSettingData"
				popper="data-source_button"
				text="配置数据源"
			></y-button>
		</div>
		<div class="config-source_setting" v-show="showConfig">
			<div class="config-source_header">
				<span class="config-source_header_title">设置数据源</span>
				<i @click="onClosePopup" class="el-icon-close"></i>
			</div>
			<y-form-item
				:staticTitle="true"
				:width="332"
				align="topToBottom"
				height="auto"
				title="数据源类型"
			>
				<y-select :options="dataSourceOptions" v-model="useapi"></y-select>
			</y-form-item>

			<!-- 选择接口 -->
			<div v-if="useapi == 'api'">
				<y-form-item
					:staticTitle="true"
					:width="332"
					align="topToBottom"
					height="auto"
					title="请选择获取数据的接口"
				>
					<el-select
						v-model="apiurl"
						filterable
						placeholder="请选择"
						@change="changeUrl"
					>
						<el-option
							v-for="item in apilist"
							:key="item.value"
							:label="item.label"
							:value="item.value"
						>
						</el-option>
					</el-select>
				</y-form-item>
				<y-button
					:height="30"
					:showIcon="false"
					:width="100"
					@click="useApi()"
					popper="data-source_button"
					text="使用此接口数据"
				></y-button>
			</div>
			<!-- 选择静态数据 -->
			<div v-if="useapi == 'static'">
				<y-form-item
					:staticTitle="true"
					:width="332"
					align="topToBottom"
					height="auto"
					title="选择数据输入方式"
				>
					<y-select :options="inputOptions" v-model="inputtype"></y-select>
				</y-form-item>
				<y-form-item
					:staticTitle="true"
					:title="dataSourceType === '数据库' ? 'SQL' : '文本'"
					:width="332"
					align="topToBottom"
					height="auto"
					v-if="inputtype == '1'"
				>
					<div>
						<monaco
							:height="200"
							:language="dataSourceType !== 'static' ? 'sql' : 'json'"
							:readOnly="false"
							:value="configTextValue"
							@blur="onBlur"
							id="config-source"
						></monaco>
					</div>
				</y-form-item>
				<y-form-item
					:staticTitle="true"
					:title="dataSourceType === '数据库' ? '表单输入' : '表单输入数据'"
					:width="332"
					align="topToBottom"
					height="auto"
					v-if="inputtype == '2'"
				>
					<div>
						<Input-by-form
							:propValue="value"
							:propconfigTextValue="configTextValue"
							@setJsonData="setJsonData"
						/>
					</div>
				</y-form-item>
				<y-form-item
					:staticTitle="true"
					:width="332"
					align="topToBottom"
					height="auto"
					title="数据响应结果为列表,列表元素包含如下字段"
				>
					<div class="config-description">
						<y-table :data="value.model">
							<y-table-column
								:width="60"
								label="字段"
								prop="field"
							></y-table-column>
							<y-table-column
								:width="60"
								label="映射"
								prop="mapping"
							></y-table-column>
							<y-table-column
								label="说明"
								prop="description"
								width="auto"
							></y-table-column>
						</y-table>
					</div>
				</y-form-item>
				<y-form-item
					:staticTitle="true"
					:width="332"
					align="topToBottom"
					height="auto"
					title="数据响应结果(只读)"
				>
					<div>
						<monaco
							:height="350"
							:value="value.json"
							id="config-source-result"
						></monaco>
					</div>
				</y-form-item>
			</div>
		</div>
	</div>
</template>

<script>
import Button from "../../base/button/src/button.vue";
import Monaco from "../monaco/monaco";
import InputByForm from "./inputByForm";
export default {
	name: "ConfigSource",
	data() {
		return {
			dataSourceType: "static",
			useapi: "static",
			dataSourceOptions: [
				{
					label: "JSON数据",
					value: "static",
				},
				// {
				// 	label: "接口数据",
				// 	value: "api",
				// },
			],
			inputOptions: [
				{
					label: "使用JSON编辑数据",
					value: "1",
				},
				{
					label: "使用表单编辑数据",
					value: "2",
				},
			],
			showConfig: false,
			dataSourceListDefault: "选择已有数据源",
			dataSourceList: [],
			inputtype: "2",
			apilist: [],
			apiurl: "",
		};
	},
	props: {
		value: Object,
	},
	created() {
		this.dataSourceType = this.value.dataType;
		this.$axios
			.post("/connection/all")
			.then((res) => {
				if (res.code === 200) {
					res.body.forEach((element) => {
						this.dataSourceList.push({
							label: element.dbconnectionname,
							value: element._id,
						});
						this.dataSourceListDefault = this.value.data.connectionSourceId
							? this.value.data.connectionSourceId
							: "选择已有数据源";
					});
				}
			})
			.catch((e) => {
				console.warn(e.message);
			});
		this.$axios.post("/apiserve/getapi", this.apiForm).then((res) => {
			if (res.code === 200) {
				if (res.body) {
					const tempmaplist = res.body.map((item) => {
						if (item._id && item.apiname) {
							return {
								value: item._id,
								label: item.apiname,
							};
						}
					});
					this.apilist = tempmaplist;
				}
			}
		});
		if (this.value.apiurl && this.value.apiurl !== "") {
			this.apiurl = this.value.apiurl;
			this.useApi();
		}
	},
	mounted() {},
	computed: {
		configTextValue() {
			if (this.value.dataType === "static") {
				return this.value.data.staticJson;
			} else {
				return this.value.data.sql;
			}
		},
	},
	methods: {
		changeUrl(e) {
			console.log(e);
		},
		setJsonData(v) {
			this.onBlur(v);
		},
		useApi() {
			this.$axios.post("/apiserve/useapi", { id: this.apiurl }).then((res) => {
				console.log(res);
				if (res.code === 200) {
					if (res.body) {
						this.onBlur(res.body, true);
					} else {
						this.$message.error(`从接口${this.apiurl}获取数据失败`);
					}
				} else {
					this.$message.error(`从接口${this.apiurl}获取数据失败`);
				}
			});
		},
		findDataSourceName(id) {
			let index = this.dataSourceList.findIndex((d) => d.value === id);
			if (index > -1) {
				return this.dataSourceList[index].label;
			} else {
				return "";
			}
		},
		onClosePopup() {
			this.showConfig = false;
		},
		onSettingData() {
			this.showConfig = true;
		},
		onBlur(val, isUseApi) {
			console.log("savedata", val);
			this.value.dataType = this.dataSourceType;
			isUseApi ? (this.value.apiurl = this.apiurl) : (this.value.apiurl = "");
			if (this.value.dataType === "static") {
				this.value.data.staticJson = val;
				this.value.json = val;
				this.value.data.sql = "";
				this.value.data.connectionSourceId = "";
				this.$emit("input", this.value);
			} else if (
				this.dataSourceListDefault != "选择已有数据源" &&
				this.value.data.sql != val
			) {
				let paging = this.value.data.paging ? this.value.data.paging : "";
				this.$axios
					.post("/connection/excuteSql", {
						id: this.dataSourceListDefault,
						sql: val,
						limit: this.value.data.limit,
						paging: paging,
					})
					.then((res) => {
						if (res.code === 200) {
							let json = JSON.stringify(res.body);
							this.value.json = json;
							this.value.data.staticJson = "";
							this.value.data.sql = val;
							this.value.data.connectionSourceId = this.dataSourceListDefault;
							this.$emit("input", this.value);
						}
					})
					.catch((e) => {
						console.warn(e.message);
					});
			} else {
				console.warn("请选择数据源,或者修改数据返回结果");
			}
		},
	},
	components: {
		Monaco,
		Button,
		InputByForm,
	},
	watch: {
		dataSourceType(val) {
			this.$bus.$emit("setLanguage", val !== "static" ? "sql" : "json");
		},
		showConfig(val) {
			if (val) {
				this.$bus.$emit("createMonacoInstance");
			}
		},
	},
};
</script>

<style lang="stylus" scoped>
.editor {
	width: 600px;
	height: 800px;
}
.config-source {
	.config-source_refresh {
		display: flex;
		flex-direction: row;
		align-items: center;
		.config-refresh_interval {
			width: 40px;
			margin-left: 10px;
		}
	}
	.config-source_data {
		display: flex;
		flex-direction: row;
		align-items: center;
		.data-source_title {
			flex: 1;
			span {
				background: rgb(57, 65, 77);
				padding: 2px 5px;
				margin-left: 5px;
			}
		}
	}
	.config-source_setting {
		.config-source_header {
			height: 50px;
			display: flex;
			align-items: center;
			.config-source_header_title {
				font-size: 16px;
				flex: 1;
			}
			i.el-icon-close {
				font-size: 20px;
				cursor: pointer;
			}
		}
		position: absolute;
		top: 0;
		left: 0;
		bottom: 0;
		display: flex;
		flex-direction: column;
		width: 100%;
		background: rgb(29, 33, 38);
		z-index: 1;
		padding: 10px 10px;
	}
}
</style>
